<?php
namespace Home\Model;

use Think\Model;
use Think\Page;

/**
 * 商品模型 
 */
class GoodsModel extends Model
{
    private static $obj ;
    /**
     * 筛选数据
     */
    public function screenData(array $array)
    {
        if (empty($array) || !is_array($array))
        {
            return array();
        }
    
        $array['title'] = isset($_POST['title']) ? $_POST['title'] : null;
    
        
        if($array['class_sub_id']) {
            $where['class_id'] = $_GET['class_sub_id'];
        }
        if($array['class_id']){
            $where['class_fid'] = $_GET['class_id'];
        }
        if($array['price'] == 1){
            $where['price_new'] = array('elt',100);
        }
        if($array['price'] == 2){
            $where['price_new'] = array('between','100,500');
        }
        if($array['price'] == 3){
            $where['price_new'] = array('between','500,1000');
        }
        if($array['price'] == 4){
            $where['price_new'] = array('egt',1000);
        }
        if (isset($array['xiangou']))
        {
            $where['xiangou'] = 1;
        }
        if(!empty($array['title'])){
            $where['title'] = array('like',"%".$array['title']."%");
        }
    
        $where['shangjia'] = array('eq',1);
    
        $nowPage = isset($_GET['p'])?$_GET['p']:1;
        // page方法的参数的前面部分是当前的页数使用 $_GET[p]获取
        $result = $this->field('id,title,pic_url,price_old, description')->where($where)->order('sort_num ASC')->page($nowPage.','.PAGE_SIZE)->select();
//         foreach ($result as $k => &$v){
//             $v['create_time'] = date('Y-m-d',$v['create_time']);
//         }
        //分页
        $count = $this->where($where)->count('id');		// 查询满足要求的总记录数

        $page = new \Think\Page($count,PAGE_SIZE);		// 实例化分页类 传入总记录数和每页显示的记录数
        
        $show = $page->show();		// 分页显示输出
        
        return array('result' =>$result, 'page' => $show);
    }
    
    /**
     * 商品详情 
     */
    public function find($options =array(), array $array = array(), Model $model)
    {
        if (!is_object($model) || !($model instanceof Model) || empty($array) || !is_array($array))
        {
            return array();
        }
        $data = parent::find($options);
        
        $goodsDetail = array();

        if (!empty($data)) 
        {
            //反序列化图片
            $data['pic_tuji'] = !empty($data['pic_tuji']) ? unserialize($data['pic_tuji']) : null;
            if ($data['pic_tuji']) {
                foreach ($data['pic_tuji'] as $key => &$value)
                {
                    if ( false === strpos($value, '/Uploads/goods/')) {
                        $value = '/Uploads/goods/'.$value;
                    }
                }
            }
            //发序列化套餐
            $data['taocan']   = !empty($data['taocan']) ? unserialize($data['taocan'])   : null;
            $array['id'] = intval($array['id']);
            
            //限购代码
            $result_orders_record = $model->field('id')->where('user_id = "'.$_SESSION['user_id'].'" and goods_id = "'.$array['id'].'"')->find();
            
            if(!empty($result_orders_record)){
              $goodsDetail['xiangou_yigoumai'] = 1;	//限购已购买
            }
            //限时购判断
            $goodsDetail['xianshi'] = isset($array['xianshi']) && $array['xianshi'] == 1 ? 'yes' : 'no';
            
            $xianshi=$this->where('id = "'.$array['id'].'" and xianshi_status = 1')->getField('xianshi_start,xianshi_over');
            if (!empty($xianshi))
            {
                $new[0]=array_keys($xianshi);
    
                $new[1]=array_values($xianshi);
                $start=$new[0][0];
                $over=$new[1][0];
                //限时购的时间判断
                $time=date("Y-m-d H:i:s");
                //echo $start;
                if($time<$start){
                    $cha=strtotime($start)-strtotime($time);
                    $goodsDetail['cha'] = $cha;//即将开始
                    $goodsDetail['xianshi_time'] = 0;//即将开始
                }else if($time>$over){
                    $goodsDetail['xianshi_time'] = 2;//活动截至
                }else{
                    $goodsDetail['xianshi_time'] = 1;
                }
            }
            //同时购买推荐
            $list_tuijian = $this->field('id,pic_url')->where('recommend = 1 and type = 1 and shangjia = 1')->order('create_time DESC, update_time DESC')->limit(5)->select();
            
            $goodsDetail['list_tuijian'] = $list_tuijian;
            
            $list_rexiao = $this->field('id,pic_url,price_new')->where('rexiao = 1 and type= 1 and shangjia = 1')->limit(2)->select();
            $goodsDetail['list_rexiao'] = $list_rexiao;
            
            // 用户评论
            $result_pingjia = $model->where('goods_id = "'.$array['id'].'" and (pingjia_status = 1 or pingjia_status = 2 or pingjia_status = 3)' )->order('pingjia_time DESC')->select();
            $goodsDetail['result_pingjia'] = $result_pingjia;
            $goodsDetail['goods'] = $data;
            
        }
        return $goodsDetail;
    }
    /**
     * 查询要购买的商品
     */
    public function getGoods(array $options, array $goodsNumber, $type=0)
    {
        if (!is_array($options) || empty($options) || empty($goodsNumber) || !is_array($goodsNumber)) {
            return array();
        }
        $data = parent::select($options);
        $sumMonery = 0;
        if (!empty($data))
        {
            foreach ($goodsNumber as $goodsId => $goodsNum)
            {
                foreach ($data as $primayKey => &$goods)
                {
                    if ($goodsId === intval($goods['id']))
                    {                
                        $goods['goods_num']    = $goodsNum;
                        $goods['total_monery'] = $goods['price_new'] * $goodsNum;
                        $goods['type']         = $type;
                        $sumMonery += $goods['total_monery'];
                    }
                }
            }
        }
        return array('goods_info' => $data, 'total_monery' => $sumMonery);
    }
    
    /**
     * 计算运费
     * @param $goods 商品id和数量的组合(二维数组)
     * @param $area  省份名字
     * $goods,$area
     * 数组示例: 
     * $goods=array(
     *      0=>array('id'=>1,'num'=>2),
     *      1=>array('id'=>1,'num'=>3)
     * );
     * 省份名字示例: $area='河北省';
     */
    public function countFreight($goods, $area ,  $data)
    {
        if (empty($goods) || !is_array($goods) || empty($area) || !is_string($area)) 
        {
            return false;
        }
        //获取包邮城市
        $baoyou_area = C('free');

        
        $yunfei = 0;

        $pattern = '/^\d+g$/';
        $patterns = '/^\d+g\*\d$/';
        $row = null;
        $zhongliang = 0;

        foreach ($goods as $goodsrow) 
        {
            $row = parent::find(array(
                'where' => array('id' => $goodsrow['id']),
                'field' => array('zhongliang')
            ));
            preg_match($pattern, $row['zhongliang'], $matches);
            preg_match($patterns, $row['zhongliang'], $matche);
    
            if (!empty($matches) || !empty($matche)) {
    
                $row['zhongliang'] = str_replace('g', '', $row['zhongliang']);
                $a = explode('*', $row['zhongliang']);
                $rst = 1;
                
                foreach ($a as $k) {
                    $rst *= $k;
                }
                if (($row['min_yunfei'] != 0) || ($row['is_baoyou'] == 0)) {//如果其他地方不包邮或者江浙沪皖不包邮,则算出重量，方便计费
                    $zhongliang += $rst * $goodsrow['goods_num'];
                }
                if($row['is_baoyou'] == 1){//即使上面有运费，如果江浙沪皖包邮，则直接将重量设置为0，下面计算运费就直接返回0
                    if(in_array($area,$baoyou_area)){
                        $zhongliang=0;
                    }
                }
            }
            	
            if($zhongliang==0){
                $yunfei+= 0;
            }else{
                if (!empty($data['ykg']) && $data['ykg'] == 3) {
                    if ($zhongliang <= 3000) {
                        $yunfei+= $data['money'];
                    } else {
                        $zhongliang = $zhongliang - 3000;//超出的部分
                        $times = ceil($zhongliang/1000);//算出整数的公斤数
                        $yunfei+= ($data['money']+$data['onemoney']*$times);
                    }
                } else {
                    if ($zhongliang <= 1000 && !empty($data)) {
                        $yunfei+= $data['money'];
                    } else {
                        $zhongliang = $zhongliang - 1000;//超出的部分
                        $times = ceil($zhongliang/1000);//算出整数的公斤数
                        $yunfei+= ($data['money']+$data['onemoney']*$times);
                    }
                }
            }
        }
        return $yunfei;
    }
    
    /**
     * 获取关键词商品数据 
     */
     public function getGoodsData(array $data, $checkKey = 'goods_class_id')
     {
         if (empty($data[$checkKey]))
         {
             return array();
         }
         $totalRows = $this->where(array('class_id' => array('in', $data[$checkKey]), 'shangjia' => 1, 'type' => 1, 'title' => array('like', $data['hot_words'])))->count();
          
         $page = new Page($totalRows, PAGE_SIZE);
         $goods = parent::select(array(
             'where' => array('class_id' => array('in', $data[$checkKey]), 'shangjia' => 1, 'type' => 1,'title' => array('like', $data['hot_words'])),
             'field' => array('id', 'pic_url', 'price_new', 'price_old', 'fanli_jifen', 'title', 'type'),
             'limit' => $page->firstRow. ','. $page->listRows
         ));
         return array('data' => $goods, 'page' => $page->show());
     }
     
     public static function getInitation()
     {
         return self::$obj = !(self::$obj instanceof GoodsModel) ? new self() : self::$obj;
     }
}